<template>
  <div>
    <div class="panel" v-loading="loading">
      <div class="panel-header">
        {{ $route.meta.title }}
      </div>
      <i-form
        ref="form"
        class="message-add__form"
        :items="formItems"
        :model="form"
        :rules="rules"
        label-width="140px"
      >
        <template slot="address" v-if="form.targetUser == 2">
          <el-form-item class="is-required" label="区域" prop="area">
            <HycAddressCascader v-model="form.area" :level="1" />
          </el-form-item>
        </template>
      </i-form>
    </div>
    <div class="panel-btn-wrapper">
      <el-button v-loading="submitLoading" @click="handleSave" type="success">
        保存
      </el-button>
      <el-button v-loading="submitLoading" @click="handleSend" type="primary">
        立即发送
      </el-button>
      <el-button @click="handleCancel" type="warning"> 返回 </el-button>
    </div>
  </div>
</template>
<script>
import { typeMap } from '@/utils/format'
import HycAddressCascader from '@/components/hycAddressCascader'
import { addHycMessage, hycMessageList, updateHycMessage } from '@/api/message'

const areaRules = [
  {
    required: true,
    type: 'object',
    message: '请选择地区',
  },
]

export default {
  name: 'messageAdd',
  components: { HycAddressCascader },
  mounted() {
    if (this.$route.params.id) {
      this.pageType = 'edit'

      this.loading = true
      hycMessageList({ id: this.$route.params.id })
        .then((res) => {
          let result = res.list[0] || {}

          this.form = {
            title: result.title,
            content: result.content,
            targetUser: String(result.targetUser),
          }

          if (this.form.targetUser === '2') {
            this.form.area = {}
            if (result.targetCity) {
              this.form.area.city = result.targetCity
            }

            if (result.targetProvince) {
              this.form.area.province = result.targetProvince
            }
          }

          console.log(this.form)
        })
        .catch((err) => {
          console.log(err)
        })
        .finally(() => {
          this.loading = false
        })
    }
  },
  methods: {
    handleSubmit(type) {
      this.$refs.form.validate((valid) => {
        if (!valid) return

        let params = {
          content: this.form.content,
          title: this.form.title,
          targetUser: parseInt(this.form.targetUser),
        }

        if (this.form.area && this.form.area.province) {
          params.targetProvince = this.form.area.province
        }

        if (this.form.area && this.form.area.city) {
          params.targetCity = this.form.area.city
        }

        if (type === 'save') {
          params.type = 0
        } else if (type === 'send') {
          params.type = 1
        }

        this.submitLoading = true
        if (this.pageType === 'edit') {
          params.id = this.$route.params.id
          updateHycMessage(params)
            .then(() => {
              this.$message({
                type: 'success',
                showClose: true,
                message: '编辑成功',
              })

              this.$router.push('/message/hycMessageList')
            })
            .catch((err) => {
              console.log(err)
            })
            .finally(() => {
              this.submitLoading = false
            })
        } else {
          addHycMessage(params)
            .then(() => {
              this.$message({
                type: 'success',
                showClose: true,
                message: '保存成功',
              })

              this.$router.push('/message/hycMessageList')
            })
            .catch((err) => {
              console.log(err)
            })
            .finally(() => {
              this.submitLoading = false
            })
        }
      })
    },
    handleSave() {
      this.handleSubmit('save')
    },
    handleSend() {
      this.handleSubmit('send')
    },
    handleCancel() {
      this.$router.push('/message/hycMessageList')
    },
  },
  watch: {
    'form.targetUser': {
      handler(value) {
        if (value === '2') {
          this.rules.area = areaRules
          this.$set(this.rules, 'area', areaRules)
        } else {
          delete this.rules.area
          this.$set(this.rules, 'area', [])
        }
      },
    },
  },
  computed: {
    resourceSet() {
      return this.$store.getters.resourceSet
    },
  },
  data() {
    return {
      loading: false,
      submitLoading: false,
      pageType: 'add',
      formItems: [
        {
          label: '标题',
          value: 'title',
          required: true,
          type: 'text',
          maxlength: 30,
          'show-word-limit': true,
        },
        {
          label: '内容',
          value: 'content',
          required: true,
          type: 'textarea',
          rows: 5,
          maxlength: 300,
          'show-word-limit': true,
        },
        {
          label: '发布对象',
          value: 'targetUser',
          required: true,
          type: 'radio',
          options: () => {
            return Object.keys(typeMap.targetUserType).map((item) => {
              return {
                label: item,
                text: typeMap.targetUserType[item],
              }
            })
          },
        },
        {
          slot: 'address',
        },
      ],
      form: {
        targetUser: '0',
        toCooperate: 'true',
      },
      rules: {},
    }
  },
}
</script>
<style lang="scss" scoped>
.message-add__form {
  padding-left: 20px;
  padding-right: 20px;
}
.message-add__submit {
  padding-top: 14px;
  padding-left: 110px;
}
</style>
